<template>
    <el-dialog v-model="dialogTableVisible" :title="title" :close-on-press-escape="false" :close-on-click-modal="false"
        :show-close="false" :draggable="true" @before-close="() => false" append-to-body style="width: 50%;">
        <FormBase :mode="mode" @on-submit="onSubmit" @on-cancel="handleClose">
            <div class="editor-container">
                <el-form ref="courseForm" :model="dataModel" label-width="auto" :rules="rules" style="width:100%">
                    <el-form-item :label="t('课程名称')" prop="name">
                        <el-input v-model="dataModel.name" :disabled="mode === 'view'" />
                    </el-form-item>
                    <el-form-item :label="t('课程分类')" prop="categoryId">
                        <el-cascader v-model="dataModel.categoryId" :options="categoryOptions" :props="{
                            checkStrictly: false
                        }" filterable :disabled="mode === 'view'" clearable />
                    </el-form-item>
                    <el-form-item :label="t('课程介绍')" prop="description">
                        <VRichEditor v-model="dataModel.description" :disabled="mode === 'view'"></VRichEditor>
                    </el-form-item>
                    <el-form-item :label="t('课程封面')" prop="originImg">
                        <VImage ref="uploadImage" :src="dataModel.originImg" :autoUpload="false"
                            :style="{ height: '160px', width: '160px' }" fit="contain" :disabled="mode === 'view'">
                        </VImage>
                    </el-form-item>
                    <el-form-item :label="t('视频')" prop="videoId">
                        <VVideoPlayer v-model="dataModel.videoId" :disabled="mode === 'view'"></VVideoPlayer>
                    </el-form-item>
                    <el-form-item :label="t('发起人')" prop="promoter">
                        <el-input v-model="dataModel.promoter" :disabled="mode === 'view'" />
                    </el-form-item>
                    <el-form-item :label="t('演讲人')" prop="speaker">
                        <el-input v-model="dataModel.speaker" :disabled="mode === 'view'" />
                    </el-form-item>
                </el-form>
            </div>
        </FormBase>
    </el-dialog>
</template>
<script setup lang="ts">
import { Ref, computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue';
import { t } from '@/common/locale';
import { FormRules } from 'element-plus';
import { add, getDetail, update } from '@/api/course';
import elHelper from '@/common/elHelper';
import { getCategoryOptions } from '@/api/category';
import VImage from '@/components/other/VImage.vue';
import VRichEditor from '@/components/other/VRichEditor.vue';
import VVideoPlayer from '../other/VVideoPlayer.vue';
import FormBase from '../layout/FormBase.vue';
import comFunc from '@/common/comFunc';

const props = defineProps({
    data: {
        type: Object,
        default: {}
    },
    mode: {
        type: String,
        validator: (val: string) => {
            return ['add', 'modify', 'view'].includes(val)
        },
        default: 'add'
    },
    show: {
        type: Boolean,
        default: false
    }
})
const emit = defineEmits(['onSubmited', 'update:show'])
const title = computed(() => {
    switch (props.mode) {
        case 'add':
            return t('新增')
        case 'modify':
            return t('修改')
        case 'view':
            return t('查看')
    }
})

const dataModel: CourseDataModel = reactive({
    name: '',
    major: '',
    description: '',
    title: '',
    originImg: '',
    objectId: '',
    thumbImg: ''
})
Object.assign(dataModel, props.data)
const mode = ref(props.mode)
const dialogTableVisible = ref(false)
const courseForm = ref()
const uploadImage = ref()
const categoryOptions: Ref<CategorySelectOption[]> = ref([])
const rules = reactive<FormRules<CourseDataModel>>({
    name: [
        { required: true, message: t('请输入课程名称'), trigger: 'blur' }
    ],
    categoryId: [
        { required: true, message: t('请选择课程分类'), trigger: 'blur' }
    ],

})
watch(() => props.show, (val) => {
    dialogTableVisible.value = val
    if (val) {
        Object.assign(dataModel, props.data)
        mode.value = props.mode
        getInfo()
    } else {
        dialogTableVisible.value = val
        dataModel.categoryId = ''
        dataModel.description = ''
        dataModel.name = ''
        dataModel.objectId = ''
        dataModel.originImg = ''
        dataModel.thumbImg = ''
        dataModel.speaker = ''
        dataModel.promoter = ''
        dataModel.videoId = ''
        uploadImage.value?.clear()
    }
})
const onSubmit = async () => {
    let valid = await courseForm.value.validate((valid, invalidFields) => {
        if (!valid) {
            elHelper.showErrorMsg('校验失败：请修改后再提交')
        }
        return valid
    })
    if (valid) {
        if (Array.isArray(dataModel.categoryId)) {
            let arr = dataModel.categoryId as string[]
            dataModel.categoryId = arr[arr.length - 1]
        }
        const reUpload = await uploadImage.value?.upload()
        if (!reUpload.isSuccess) {
            elHelper.showErrorMsg(reUpload.msg)
            return
        }
        dataModel.originImg = reUpload.path
        if (mode.value === 'add') {
            const re = await add(dataModel)
            if (re.isSuccess) {
                emit('onSubmited', re.data!)
                elHelper.showSuccessMsg('操作成功')
                handleClose()
            } else {
                elHelper.showErrorMsg(re.msg)
            }
        } else {
            const re = await update(dataModel)
            if (re.isSuccess) {
                emit('onSubmited', re.data!)
                elHelper.showSuccessMsg('操作成功')
                handleClose()
            } else {
                elHelper.showErrorMsg(re.msg)
            }
        }
    }
}
const handleClose = () => {
    dialogTableVisible.value = false
    emit('update:show', false)
}
const getInfo = async () => {
    if (!dataModel.objectId) return
    const re = await getDetail(comFunc.nvl(dataModel.objectId))
    if (re.isSuccess) {
        Object.assign(dataModel, re.data)
    } else {
        elHelper.showErrorMsg(re.msg)
    }
}
onMounted(async () => {
    const l = await getCategoryOptions('COURSE')
    categoryOptions.value = l
})
onUnmounted(() => {
    handleClose()
})
</script>
<style lang="scss" scoped>
.editor-container {
    width: 98%;
    height: 70vh;
    text-align: center;
}
</style>